package com.qy.controller.app;

import com.qy.base.core.*;
import com.qy.base.utils.DateUtil;
import com.qy.base.utils.DownLoadImgFromNet;
import com.qy.base.utils.UploadFile;
import com.qy.base.utils.weixin.utils.HttpCommonUtil;
import com.qy.base.utils.weixin.utils.WXAPPConfigUtil;
import com.qy.model.*;
import com.qy.service.*;
import com.github.pagehelper.PageHelper;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

import static com.qy.base.utils.alipay.config.PayConfig.appid;
import static com.qy.base.utils.alipay.util.UtilDate.getDate;

/**
 * Created by zaq on 2018/07/10.
 */
@RestController
@RequestMapping("app/member")
public class MemberController {
    @Resource
    private MemberService memberService;

    @Resource
    private PolicyOrderService policyOrderService;

    @Resource
    private RewardOrderService rewardOrderService;

    @Resource
    private MemberOrderService memberOrderService;

    @Resource
    private ClueService clueService;

    @Resource
    private WithdrawService withdrawService;

    @Resource
    private ShareService shareService;

    @PostMapping("/add")
    public Result add(@RequestBody Member member) {
        memberService.save(member);
        return ResultGenerator.successResult();
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody Integer id) {
        memberService.deleteById(id);
        return ResultGenerator.successResult();
    }

    @PostMapping("/update")
    public Result update(@RequestBody Member member) {
        memberService.update(member);
        return ResultGenerator.successResult();
    }

    @GetMapping("/detail")
    public Result detail(@RequestParam Integer id) {
        Member member = memberService.findById(id);
        return ResultGenerator.successResult(member);
    }

    @GetMapping("/list")
    public Result list(PageBean<Member> page) {
        PageHelper.startPage(page.getPageNum(), page.getSize());
        List<Member> list = memberService.findAll();
        page.setList(list);
        return ResultGenerator.successResult(page);
    }

    //获取openid
    @GetMapping("/getOpenid")
    public Result getOpenId(String code) {
        if (code == null || code.isEmpty()) {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }
        String access_token_str = HttpCommonUtil.httpsRequest("https://api.weixin.qq.com/sns/jscode2session?appid=" + WXAPPConfigUtil.APPID + "&secret=" + WXAPPConfigUtil.APPSERCET + "&js_code=" + code + "&grant_type=authorization_code", "GET", null);
        JSONObject access_token_obj = JSONObject.fromObject(access_token_str);
        String openid = access_token_obj.get("openid").toString();
        List<Member> list = memberService.selectMemberListByOpenid(openid);
        Member member = new Member();
        if (list.size() == 0) {
            member.setWechat_id(openid);
            member.setAdd_time(DateUtil.getNowTimestamp());
            memberService.save(member);
        } else {
            member = list.get(0);
        }
        if (member.getLogin_number() == 0) {
            member.setMember_surplus_number(member.getMember_surplus_number() + 3);
        }
        member.setLogin_number(member.getLogin_number() + 1);
        memberService.update(member);
        return ResultGenerator.successResult(member);
    }

    //小程序登录
    @PostMapping("/login")
    public Result login(@RequestBody Member member) throws Exception {
        if (member.getId() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        Member member1 = memberService.findById(member.getId());
        if (member.getHead_picture() != null && !member.getHead_picture().isEmpty()) {
            if (member.getHead_picture().contains("http")) {
                member1.setHead_picture(DownLoadImgFromNet.downloadImg(member.getHead_picture()));
            } else {
                member1.setHead_picture(UploadFile.uploadBase64(member.getHead_picture()));
            }
        }
        if (member.getNickname() != null && !member.getNickname().isEmpty()) {
            member1.setNickname(member.getNickname());
        }
        memberService.update(member1);

        return ResultGenerator.successResult(member1);
    }


    //搜索
    @GetMapping("/search")
    public Result search(String searchType, String searchContent) {
        if (searchType == null || searchType.isEmpty()) {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }
        Map map = new HashMap();
        if (searchContent.contains("；") || searchContent.contains(";")) {
            String[] strings = searchContent.replaceAll("；", ";").split(";");
            String searchContent1 = strings[0];
            String searchContent2 = strings[1];
            if (searchType.equals("1")) {
                List<Map> policyList = memberService.selectPolicy(searchContent1);
                map.put("policyList", policyList);
            } else if (searchType.equals("2")) {
                List<Map> unitList = memberService.selectUnit(searchContent1);
                map.put("unitList", unitList);
            } else if (searchType.equals("3")) {
                List<Map> chargeList = memberService.selectCharge(searchContent1);
                map.put("chargeList", chargeList);
            } else if (searchType.equals("4")) {
                List<Map> list = memberService.selectAllByCity(searchContent1);
                map.put("list", list);
            } else if (searchType.equals("1,2")) {
                List<Map> policyList = memberService.selectPolicy(searchContent1);
                List<Map> unitList = memberService.selectUnit(searchContent2);
                map.put("policyList", policyList);
                map.put("unitList", unitList);
            } else if (searchType.equals("1,3")) {
                List<Map> policyList = memberService.selectPolicy(searchContent1);
                List<Map> chargeList = memberService.selectCharge(searchContent2);
                map.put("policyList", policyList);
                map.put("chargeList", chargeList);
            } else if (searchType.equals("1,4")) {
                List<Map> policyList = memberService.selectPolicys(searchContent1, searchContent2);
                map.put("policyList", policyList);
            } else if (searchType.equals("2,3")) {
                List<Map> unitList = memberService.selectUnit(searchContent1);
                List<Map> chargeList = memberService.selectCharge(searchContent2);
                map.put("unitList", unitList);
                map.put("chargeList", chargeList);
            } else if (searchType.equals("2,4")) {
                List<Map> unitList = memberService.selectUnits(searchContent1, searchContent2);
                map.put("unitList", unitList);
            } else if (searchType.equals("3,4")) {
                List<Map> chargeList = memberService.selectCharges(searchContent1, searchContent2);
                map.put("chargeList", chargeList);
            }
        } else {
            if (searchType.equals("1")) {
                List<Map> policyList = memberService.selectPolicy(searchContent);
                map.put("policyList", policyList);
            } else if (searchType.equals("2")) {
                List<Map> unitList = memberService.selectUnit(searchContent);
                map.put("unitList", unitList);
            } else if (searchType.equals("3")) {
                List<Map> chargeList = memberService.selectCharge(searchContent);
                map.put("chargeList", chargeList);
            } else if (searchType.equals("4")) {
                List<Map> list = memberService.selectAllByCity(searchContent);
                map.put("list", list);
            } else if (searchType.equals("1,2")) {
                List<Map> policyList = memberService.selectPolicy(searchContent);
                List<Map> unitList = memberService.selectUnit(searchContent);
                map.put("policyList", policyList);
                map.put("unitList", unitList);
            } else if (searchType.equals("1,3")) {
                List<Map> policyList = memberService.selectPolicy(searchContent);
                List<Map> chargeList = memberService.selectCharge(searchContent);
                map.put("policyList", policyList);
                map.put("chargeList", chargeList);
            } else if (searchType.equals("1,4")) {
                List<Map> policyList = memberService.selectPolicys(searchContent, searchContent);
                map.put("policyList", policyList);
            } else if (searchType.equals("2,3")) {
                List<Map> unitList = memberService.selectUnit(searchContent);
                List<Map> chargeList = memberService.selectCharge(searchContent);
                map.put("unitList", unitList);
                map.put("chargeList", chargeList);
            } else if (searchType.equals("2,4")) {
                List<Map> unitList = memberService.selectUnits(searchContent, searchContent);
                map.put("unitList", unitList);
            } else if (searchType.equals("3,4")) {
                List<Map> chargeList = memberService.selectCharges(searchContent, searchContent);
                map.put("chargeList", chargeList);
            }
        }
        return ResultGenerator.successResult(map);
    }

    //编辑个人资料
    @RequestMapping("/editData1")
    public Result editData1(Member member, HttpServletRequest request) throws Exception {
        if (member.getId() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        Member member1 = memberService.findById(member.getId());

        request.setCharacterEncoding("utf-8");  //设置编码

        String randomName = UUID.randomUUID().toString() + ".jpg";
        String imageName = getDate() + "/" + randomName;
        //服务器真正存放的路径
        String fileName = Constants.PATH_IMAGE_PATH + imageName;
        // 保存图片到本地
        File file = new File(fileName);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        //读写文件
        OutputStream out = new FileOutputStream(file);
        InputStream in = request.getPart("file").getInputStream();
        int length = 0;
        byte[] buf = new byte[1024];
//             in.read(buf); 每次读到的数据存放在buf 数组中
        while ((length = in.read(buf)) != -1) {
//                //在buf数组中取出数据写到（输出流）磁盘上
            out.write(buf, 0, length);
        }
        in.close();
        out.close();
        member1.setHead_picture(Constants.PATH_IMAGE_PATH_DB + imageName);

        if (member.getName() != null && !member.getName().isEmpty()) {
            member1.setName(member.getName());
        }
        if (member.getPhone() != null && !member.getPhone().isEmpty()) {
            if (member1.getPhone() == null || member1.getPhone().isEmpty()) {
                member1.setMember_surplus_number(member1.getMember_surplus_number() + 5);
                List<Share> shareList = shareService.selectShareListBySharedId(member.getId());
                if (shareList.size() != 0) {
                    Member member2 = memberService.findById(shareList.get(0).getShare_id());
                    member2.setMember_surplus_number(member2.getMember_surplus_number() + 20);
                    memberService.update(member2);
                }
            }
            member1.setPhone(member.getPhone());
        }
        if (member.getCompany_name() != null && !member.getCompany_name().isEmpty()) {
            member1.setCompany_name(member.getCompany_name());
        }
        if (member.getHold_office() != null && !member.getHold_office().isEmpty()) {
            member1.setHold_office(member.getHold_office());
        }
        if (member.getEmail() != null && !member.getEmail().isEmpty()) {
            member1.setEmail(member.getEmail());
        }
        memberService.update(member1);

        return ResultGenerator.successResult(member1);
    }

    //编辑个人资料
    @RequestMapping("/editData2")
    public Result editData2(@RequestBody Member member) {
        if (member.getId() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        Member member1 = memberService.findById(member.getId());

        member1.setHead_picture(member1.getHead_picture());

        if (member.getName() != null && !member.getName().isEmpty()) {
            member1.setName(member.getName());
        }
        if (member.getPhone() != null && !member.getPhone().isEmpty()) {
            if (member1.getPhone() == null || member1.getPhone().isEmpty()) {
                member1.setMember_surplus_number(member1.getMember_surplus_number() + 5);
                List<Share> shareList = shareService.selectShareListBySharedId(member.getId());
                if (shareList.size() != 0) {
                    Member member2 = memberService.findById(shareList.get(0).getShare_id());
                    member2.setMember_surplus_number(member2.getMember_surplus_number() + 20);
                    memberService.update(member2);
                }
            }
            member1.setPhone(member.getPhone());
        }
        if (member.getCompany_name() != null && !member.getCompany_name().isEmpty()) {
            member1.setCompany_name(member.getCompany_name());
        }
        if (member.getHold_office() != null && !member.getHold_office().isEmpty()) {
            member1.setHold_office(member.getHold_office());
        }
        if (member.getEmail() != null && !member.getEmail().isEmpty()) {
            member1.setEmail(member.getEmail());
        }
        memberService.update(member1);

        return ResultGenerator.successResult(member1);
    }

    //个人中心用户资料
    @GetMapping("/memberDetail")
    public Result memberDetail(Member member) {
        if (member.getId() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        Member member1 = memberService.findById(member.getId());
        return ResultGenerator.successResult(member1);
    }

    //政策数量
    @GetMapping("/policyNumber")
    public Result policyNumber(Member member) {
        if (member.getId() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        List<Map> list1 = new ArrayList<>();
        List<Map> list2 = new ArrayList<>();
        List<Map> list3 = new ArrayList<>();
        list1 = memberService.selectPolicyList(member);
        list2 = memberService.selectUnitList(member);
        list3 = memberService.selectChargeList(member);

        Map<String, Object> map = new HashMap<>();
        map.put("policyNumber", list1.size());
        map.put("unitNumber", list2.size());
        map.put("chargeNumber", list3.size());

        return ResultGenerator.successResult(map);
    }

    //我的政策库
    @GetMapping("/myPolicyLibrary")
    public Result myPolicyLibrary(PageBean<Map> page, Member member) {
        if (member.getId() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        List<Map> list = new ArrayList<>();
        if (member.getType() == 1) {
            PageHelper.startPage(page.getPageNum(), page.getSize(), "add_time desc");
            list = memberService.selectPolicyList(member);
        }
        if (member.getType() == 2) {
            PageHelper.startPage(page.getPageNum(), page.getSize(), "add_time desc");
            list = memberService.selectUnitList(member);
        }
        if (member.getType() == 3) {
            PageHelper.startPage(page.getPageNum(), page.getSize(), "add_time desc");
            list = memberService.selectChargeList(member);
        }
        page.setList(list);
        return ResultGenerator.successResult(page);
    }

    //绑定银行卡
    @PostMapping("/bindBankCard")
    public Result bindBankCard(@RequestBody Member member) {
        if (member.getId() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        Member member1 = memberService.findById(member.getId());
        member1.setCard_holder(member.getCard_holder());
        member1.setCard_number(member.getCard_number());
        member1.setId_card(member.getId_card());
        member1.setReserve_phone(member.getReserve_phone());
        member1.setBank_name(member.getBank_name());
        memberService.update(member1);
        return ResultGenerator.successResult();
    }

    //记录
    @GetMapping("record")
    public Result record(PageBean<Map> page, Member member) {
        if (member.getId() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }

        PageHelper.startPage(page.getPageNum(), page.getSize());
        List<Map> list = memberService.selectRecordByUserId(member);
        page.setList(list);

        return ResultGenerator.successResult(page);
    }


}
